package com.xc.service.Impl;

import com.xc.dao.AccountMapper;
import com.xc.dao.AccountRoleMapper;
import com.xc.pojo.Account;
import com.xc.pojo.AccountRole;
import com.xc.service.AccountService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;

    @Resource
    private AccountRoleMapper accountRoleMapper;
    /**
     * 添加用户
     * @param account
     * @return
     */
    public int addAccount(Account account) {
        account.setRegistTime(new Date());
        account.setPassword(new BCryptPasswordEncoder().encode(account.getPassword()));//密码加密
        account.setStatus(1);
        int count = accountMapper.addAccount(account);
        if (count>0){
            //添加角色关系(1:普通用户  2：vip)   account.getId()为空 在映射文件里添加配置
            accountRoleMapper.addAccountRole(account.getId());
        }
        return count;
    }

    /**
     * 根据用户名查询用户
     * @param loginName
     * @return
     */
    public Account queryAccountByName(String loginName) {
        return accountMapper.queryAccountByName(loginName);
    }

    public Account getAccountByName(String name) {
        return accountMapper.getAccountByName(name);
    }

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //创建角色列表集合
        List<SimpleGrantedAuthority> authorities=new ArrayList<SimpleGrantedAuthority>();
        //调用方法查询用户信息
        Account account = accountMapper.queryAccountByName(username);
        //循环遍历角色列表
        for (AccountRole accountRole : account.getRoleList()) {
            authorities.add(new SimpleGrantedAuthority(accountRole.getRoleCode()));
        }
        //创建user对象
        User user=new User(
                account.getLoginName(),
                account.getPassword(),
                account.getStatus()==1,
                true,
                true,
                true,
                authorities);
        return user;
    }
}
